var utils = require("./utils");
var files_logger = require("./files_logger");

if (!requestScreenCapture()) {
  toastLog("请求截图权限失败");
  exit();
}
var OCR_UTIL_CONST_CHAR_MATCH_MAP = {
  搜: ["嫂", "樓", "接", "楼"],
  赚: ["廉", "嫌", "賺", "兼"],
  看: ["着", "春"],
  文: ["女"],
  章: ["拿"],
  钱: ["线"],
  觉: ["党"],
  户: ["戶"],
  索: ["素"],
  开: ["升", "研"],
  金: ["全"],
  积: ["枳"],
  币: ["市"],
  现: ["現"],
  领: ["領", "颌"],
  读: ["渎"],
  额: ["額"],
  取: ["驭"],
  视: ["规", "初"],
  享: ["亨"],
  兑: ["兌"],
  提: ["堤"],
  体: ["休"],
  才: ["オ"],
  街: ["衔"],
  城: ["械"],
  间: ["闻"],
  来: ["來"],
  十: ["+"],
};

var ocr_utils = {
  get_reg_exp(content) {
    var reg_exp_string = content
      .split("")
      .map(function (item) {
        var match = OCR_UTIL_CONST_CHAR_MATCH_MAP[item];
        var piece = match
          ? "[" + match.concat(item).join("") + "]+"
          : "[" + item + "]+";
        return piece + `\\s*`;
      })
      .join("");
    var reg_exp = new RegExp(reg_exp_string, "gi");
    return {
      text: content,
      reg_exp: reg_exp,
    };
  },
  toArray(array_like) {
    var array = [];
    for (var i = 0; i < array_like.length; i++) {
      array.push(array_like[i]);
    }
    return array;
  },
  screen_exists_text_all(content, log_ocr_texts) {
    var logger = utils.create_logger("ocr_util screen_exists_text_all: ");
    logger("");
    if (!Array.isArray(content)) {
      content = [content];
    }
    var content_configs = content.map((item) => {
      return {
        text: content,
        reg_exp: this.get_reg_exp(item).reg_exp,
        find: null,
      };
    });
    if (log_ocr_texts) {
      logger(
        "正则表达式是--" +
          content_configs.map((item) => item.reg_exp.toString()).join(" || ") +
          "--"
      );
    }
    var startTime = Date.now();
    var capture_img = captureScreen();
    if (!capture_img) {
      toastLog("截图失败");
    }
    var endTime = Date.now();
    logger("截图耗费-" + (endTime - startTime) / 1000 + "-s");
    var capture_img_orc_results = this.toArray(
      gmlkit.ocr(capture_img, "zh").toArray(3)
    );
    capture_img.recycle();
    for (var i = 0; i < capture_img_orc_results.length; i++) {
      var item = capture_img_orc_results[i];
      for (var j = 0; j < content_configs.length; j++) {
        var content_config = content_configs[j];
        if (!content_config.find && content_config.reg_exp.test(item.text)) {
          content_config.find = item;
          break;
        }
      }
      if (content_configs.every((item) => item.find)) {
        break;
      }
    }

    if (content_configs.some((item) => !item.find)) {
      if (log_ocr_texts) {
        var no_finds = content_configs
          .filter((item) => !item.find)
          .map((item) => item.text)
          .join(" || ");
        logger("没找到--" + no_finds + "--");
        var file_name = files_logger.get_file_name();
        logger("已经记录到--ocr_error--,文件名字为--" + file_name + "--");
        files_logger.write(
          "ocr_result",
          "error",
          "要找的是：" +
            no_finds +
            "\n" +
            "但是没找到，下面是ocr识别的结果：" +
            "\n" +
            capture_img_orc_results.map((item) => item.text).join("\n"),
          file_name
        );
      }
      return false;
    }
    return true;
  },
  screen_exists_text_one(content, log_ocr_texts) {
    var logger = utils.create_logger("ocr_util screen_exists_text_one: ");
    if (!Array.isArray(content)) {
      content = [content];
    }
    var content_configs = content.map((item) => {
      return {
        text: content,
        reg_exp: this.get_reg_exp(item).reg_exp,
        find: null,
      };
    });
    if (log_ocr_texts) {
      logger(
        "正则表达式是--" +
          content_configs.map((item) => item.reg_exp.toString()).join(" || ") +
          "--"
      );
    }
    var startTime = Date.now();
    var capture_img = captureScreen();
    if (!capture_img) {
      toastLog("截图失败");
    }
    var endTime = Date.now();
    logger("截图耗费-" + (endTime - startTime) / 1000 + "-s");
    var capture_img_orc_results = this.toArray(
      gmlkit.ocr(capture_img, "zh").toArray(3)
    );
    capture_img.recycle();
    for (var i = 0; i < capture_img_orc_results.length; i++) {
      var item = capture_img_orc_results[i];
      for (var j = 0; j < content_configs.length; j++) {
        var content_config = content_configs[j];
        if (content_config.reg_exp.test(item.text)) {
          content_config.find = item;
          return item;
        }
      }
    }

    if (content_configs.every((item) => !item.find)) {
      if (log_ocr_texts) {
        var no_finds = content_configs.map((item) => item.text).join(" && ");
        logger("没找到--" + no_finds + "--");
        var file_name = files_logger.get_file_name();
        logger("已经记录到--ocr_error--,文件名字为--" + file_name + "--");
        files_logger.write(
          "ocr_result",
          "error",
          "要找的是：" +
            no_finds +
            "\n" +
            "但是没找到，下面是ocr识别的结果：" +
            "\n" +
            capture_img_orc_results.map((item) => item.text).join("\n"),
          file_name
        );
      }
      return false;
    }
    return true;
  },
  capture_then_log_text() {
    var logger = utils.create_logger("capture_then_log_text: ");
    var startTime = Date.now();
    var capture_img = captureScreen();
    if (!capture_img) {
      toastLog("截图失败");
    }
    var endTime = Date.now();
    logger("截图耗费-" + (endTime - startTime) / 1000 + "-s");
    var capture_img_orc_results = this.toArray(
      gmlkit.ocr(capture_img, "zh").toArray(3)
    );
    capture_img.recycle();
    console.log(capture_img_orc_results.map((item) => item.text).join("\n"));
  },
  capture_exists_text(content, log_ocr_texts) {
    if (!Array.isArray(content)) {
      content = [content];
    }
    var configs = content.map((item) => {
      return this.get_reg_exp(item);
    });
    if (log_ocr_texts) {
      console.log(
        "ocr_utils capture_exists_text: " +
          "正则表达式是：--" +
          configs.map((item) => item.reg_exp).join(" || ") +
          "--"
      );
    }
    return this.capture_exists_match(configs, log_ocr_texts);
  },
  capture_exists_match(reg_exp_configs, log_ocr_texts) {
    var startTime = Date.now();
    var capture_img = captureScreen();
    if (!capture_img) {
      toastLog("截图失败");
    }
    var endTime = Date.now();
    logger("截图耗费-" + (endTime - startTime) / 1000 + "-s");
    var capture_img_orc_results = this.toArray(
      gmlkit.ocr(capture_img, "zh").toArray(3)
    );
    capture_img.recycle();
    for (var i = 0; i < capture_img_orc_results.length; i++) {
      var item = capture_img_orc_results[i];
      if (
        reg_exp_configs.some((reg_exp_config) => {
          return reg_exp_config.reg_exp.test(item.text);
        })
      ) {
        console.log("找到--" + item.text + "--");
        return item;
      }
    }
    console.log(
      "ocr_util capture_exists_match: 没找到: " +
        reg_exp_configs.map((item) => item.text).join(" || ")
    );
    if (log_ocr_texts) {
      var file_name = files_logger.get_file_name();
      console.log("已经记录到--ocr_error--,文件名字为--" + file_name + "--");
      files_logger.write(
        "ocr_result",
        "error",
        "要找的是：" +
          reg_exp_configs.map((item) => item.text).join(" || ") +
          "\n" +
          "但是没找到，下面是ocr识别的结果：" +
          "\n" +
          capture_img_orc_results.map((item) => item.text).join("\n"),
        file_name
      );
    }
  },
  find_text(
    content,
    log_ocr_texts,
    if_is_end,
    max_swipe_times,
    swipe_instance
  ) {
    if (!Array.isArray(content)) {
      content = [content];
    }
    max_swipe_times = max_swipe_times || 10;
    log_ocr_texts = log_ocr_texts || false;
    swipe_instance = swipe_instance || 200;
    var reg_exp_configs = content.map((item) => {
      return this.get_reg_exp(item);
    });
    while (max_swipe_times > 0) {
      var result = this.capture_exists_match(reg_exp_configs, log_ocr_texts);
      if (result) {
        return result;
      }
      swipe(
        (device.width / 2) * utils.get_swipe_times(98, 2),
        (device.height / 2) * utils.get_swipe_times(98, 2),
        (device.width / 2) * utils.get_swipe_times(98, 2),
        (device.height / 2 - swipe_instance) * utils.get_swipe_times(98, 2),
        utils.get_random_interval(2, 0, 3, 100)
      );
      sleep(2 * 1000);
      max_swipe_times -= 1;
      if (if_is_end && if_is_end()) {
        break;
      }
    }
  },
  find_text_all(
    content,
    log_ocr_texts,
    if_is_end,
    max_swipe_times,
    swipe_instance
  ) {
    var logger = utils.create_logger("ocr_util find_text_all: ");
    if (!Array.isArray(content)) {
      content = [content];
    }
    var content_configs = content.map((item) => {
      return {
        text: item,
        reg_exp: this.get_reg_exp(item).reg_exp,
        result: null,
      };
    });
    if (log_ocr_texts) {
      logger(
        "正则表达式是： --" +
          content_configs.map((item) => item.reg_exp).join(" || ") +
          "--"
      );
    }
    max_swipe_times = max_swipe_times || 10;
    log_ocr_texts = log_ocr_texts || false;
    swipe_instance = swipe_instance || (device.height / 10) * 1;
    var ocr_text_results = [];
    while (max_swipe_times > 0) {
      var startTime = Date.now();
      var capture_img = captureScreen();
      if (!capture_img) {
        toastLog("截图失败");
      }
      var endTime = Date.now();
      logger("截图耗费-" + (endTime - startTime) / 1000 + "-s");
      var capture_orc_results = this.toArray(
        gmlkit.ocr(capture_img, "zh").toArray(3)
      );
      capture_img.recycle();
      for (var i = 0; i < capture_orc_results.length; i++) {
        var item = capture_orc_results[i];
        for (var j = 0; j < content_configs.length; j++) {
          var content_config = content_configs[j];
          var text = content_config.text;
          var reg_exp = content_config.reg_exp;
          if (reg_exp.test(item.text)) {
            ocr_text_results.push({
              text,
              reg_exp,
              result: item,
            });
            logger("找到--" + item.text + "--");
            break;
          }
        }
        if (ocr_text_results.length == content_configs.length) {
          break;
        }
      }
      if (ocr_text_results.length > 0) {
        return ocr_text_results;
      }
      if (ocr_text_results.length == 0) {
        if (log_ocr_texts) {
          var file_name = files_logger.get_file_name();
          logger(
            "当前页面没有找到--" +
              content_configs.map((item) => item.text).join(" || ") +
              "--,已经记录在--ocr_error--,文件名字为--" +
              file_name +
              "--"
          );
          files_logger.write(
            "ocr_result",
            "error",
            "要找的是：" +
              content_configs.map((item) => item.text).join(" || ") +
              "\n" +
              "但是没找到，下面是ocr识别的结果：" +
              "\n" +
              capture_orc_results.map((item) => item.text).join("\n"),
            file_name
          );
        } else {
          logger(
            "当前页面没有找到--" +
              content_configs.map((item) => item.text).join(" || ")
          );
        }
      }
      swipe(
        (device.width / 2) * utils.get_swipe_times(98, 2),
        (device.height / 2) * utils.get_swipe_times(98, 2),
        (device.width / 2) * utils.get_swipe_times(98, 2),
        (device.height / 2) * utils.get_swipe_times(98, 2) - swipe_instance,
        utils.get_random_interval(2, 0, 3, 100)
      );
      sleep(2 * 1000);
      max_swipe_times -= 1;
      if (if_is_end && if_is_end()) {
        return ocr_text_results;
      }
    }
    return ocr_text_results;
  },
};

module.exports = ocr_utils;
